<template>
  <!-- 要注意：antD（v-model:value=）和Element（v-model）的绑定语法 -->
  <el-cascader
    :options="myOptions"
    size="small"
    placeholder="请选择"
    v-bind="attrs"
  />
</template>
<script setup>
import { post, get } from 'server/request'
const emit = defineEmits(['update:value'])
const attrs = useAttrs()
const props = defineProps({
  value: [String, Number, Array],
  url: String,
  params: {
    type: Object,
    default: () => {
      return {}
    }
  },
  /* 不知道immediate什么意思 */
  immediate: {
    type: Boolean,
    default: true
  },
  options: {
    type: Array,
    default: () => []
  },
  method: {
    type: String,
    default: 'post'
  },
  fieldNames: {
    type: Object
  }
})

const AXIOS_METHOD = {
  post: post,
  get: get
}

const myOptions = ref(
  [
    {
      value: '',
      label: 'All'
    },
    {
      value: 'Option1',
      label: 'Option1'
    },
    {
      value: 'Option2',
      label: 'Option2'
    },
    {
      value: 'Option3',
      label: 'Option3'
    }
  ] || props.options
)
let reqParams = toRaw(props.params)

const getServerUrl = () => {
  return `${import.meta.env.VITE_APP_CONFIG}/${props.url}`
}

/* func：获取数据源 */
const getOptions = async () => {
  const { success, data, retInfo } = await AXIOS_METHOD[
    props.method.toLowerCase() //健壮代码：这里用小写处理一下
  ](getServerUrl(), reqParams)
  if (success) {
    myOptions.value = optionsShaking(data) // 数据清洗
  } else {
    ElMessage.error(retInfo)
  }
}

/* 组件需要的数据结构：
[
  {
  value:'',
  label:'',
  children:[..]
  },
  ...
]
*/
/* func：数据清洗 */
const optionsShaking = options => {
  const result = options.map(item => {
    return {
      label: item.reason,
      value: item.id,
      children: item.childList ? optionsShaking(item.childList) : []
    }
  })
  return result
}

/* element不需要,attrs直接把v-model也透传了 */
// const checkedsValue = computed({
//   get() {
//     return props.value
//   },
//   set(value) {
//     emit('update:value', value)
//   }
// })

onMounted(() => {
  if (props.url) {
    props.immediate && getOptions()
  }
})
</script>
<style lang="scss" scoped></style>
